package edu.whu.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.whu.demo.dao.OperationDao;
import edu.whu.demo.domain.User;
import edu.whu.demo.dao.UserDao;
import edu.whu.demo.exception.AccountException;
import edu.whu.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 
 * @since 2022-11-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {

    @Autowired
    UserDao userDao;

    @Value("${PicPath.local}")
    String localPath;

    @Value("${PicPath.remote}")
    String remotePath;

    @Value("${server.port}")
    String port;

    @Value("${MyDomain}")
    String domain;

    @Override
    public User getAccount(Long id){
        User user =  userDao.selectById(id);
        // 不向前端发送密码
//        user.setPassword("");
        return user;
    }


    @Override
    public void deleteAccount(Long id) {
        //删除用户
        userDao.deleteById(id);
    }

    @Override
    public void updateAccount(Long id,User user) throws AccountException {
        if(userDao.findByName(user.getName()) != null && !userDao.findByName(user.getName()).getUid().equals(id)){
            throw new AccountException("用户名已存在");
        }
        else userDao.updateById(user);
    }


    @Override
    public IPage<User> findAccount(Map<String, Object> condition, Integer pageNum, Integer pageSize) {
        //查找用户信息。
        Page<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> qw = new QueryWrapper<>();
        System.out.println(condition);
        if(condition.containsKey("keyword"))
            qw.eq("p.role","normal").and(wrapper -> wrapper.like( "p.name", condition.get("keyword"))
                .or().like("p.email", condition.get("keyword")));
        else
            qw.eq("p.role","normal");

        //默认升序
        if(!condition.containsKey("order"))
            qw.orderByAsc("name");
        else qw.orderBy(condition.containsKey("order"), (Boolean) condition.get("order"),"name");

        userDao.findAccount(page,qw);
        return page;
    }

    @Override
    public User getUserByName(String username){
        //待商榷
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("name",username);
        List<User> user =  userDao.selectList(qw);
        return user.get(0);
    }

    @Override
    public boolean userLogin(String name,String password){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("name",name);
        List<User> users = userDao.selectList(qw);
        if (users==null){
            return false;
        }else if (!users.get(0).getPassword().equals(password)){
            return false;
        }else {
            return true;
        }
    }


    @Override
    public boolean userRegisterSms(String name){
        QueryWrapper<User> qw = new QueryWrapper();
        qw.eq("name",name);
        List<User> users = userDao.selectList(qw);
        if (users.size()==0){
            return true;
        }else {
            return false;
        }
    }
    @Override
    public void userRegister(User user){
        user.setRole("normal");
        user.setPicture("http://127.0.0.1:8080/static/image/管理员.png");
        userDao.insert(user);
    }

    @Override
    public boolean userPasswordChange(String name,String password,String newPassword){
        User user = userDao.findByName(name);
        if (user==null){
            return false;
        }else if(!user.getPassword().equals(password)){
            return false;
        }else {
            user.setPassword(newPassword);
            userDao.updateById(user);
            return true;
        }
    }

    @Override
    public boolean userPasswordBySms(String name,String newPassword){
        User user = userDao.findByName(name);
        if (user==null){
            return false;
        }else {
            user.setPassword(newPassword);
            userDao.updateById(user);
            return true;
        }
    }
    @Override
    public String userGetEmail(String name){
        User user = userDao.findByName(name);
        if (user==null){
            throw new RuntimeException("没有找到该用户");
        }else {
            return user.getEmail();
        }
    }
    @Override
    public String uploadPicture(Long id, MultipartFile pic) throws AccountException {
        User user = userDao.selectById(id);
        String fileName =  UUID.randomUUID()+".png";
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(localPath+fileName);
            fileOutputStream.write(pic.getBytes());
        } catch (IOException e) {
            throw new AccountException(e.getMessage());
        }

        String newPic = "http://"+domain+":"+port+"/"+remotePath+fileName;

        user.setPicture(newPic);

        userDao.updateById(user);

        return newPic;
    }


}
